package com.huawei.netopen.message;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

import com.huawei.netopen.R;
import com.huawei.netopen.common.log.Logger;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

/**
 * 应用启动图标未读消息数显示 (效果如：QQ、微信、未读短信 等应用图标)<br/>
 * 依赖于第三方手机厂商(如：小米、三星)的Launcher定制、原生系统不支持该特性<br/>
 * 
 * @author FingerArt FingerArt.me
 * @date 2016年1月2日 下午1:01:58
 *       
 */
@SuppressLint("DefaultLocale")
public final class BadgeUtil
{
    private BadgeUtil()
    {
    }
    
    public static boolean isMiUi()
    {
        return Build.MANUFACTURER.equalsIgnoreCase("Xiaomi");
    }
    
    /**
     * 设置未读消息
     * 
     * @param context
     * @param count 未读消息数量
     */
    public static void setBadgeCount(Context context, int count)
    {
        if (count <= 0)
        {
            count = 0;
        }
        
        if (Build.MANUFACTURER.equalsIgnoreCase("sony"))
        {
            sendToSony(context, count);
        }
        else if (Build.MANUFACTURER.toLowerCase(Locale.US).contains("samsung"))
        {
            sendToSamsumg(context, count);
        }
        else if (Build.MANUFACTURER.equalsIgnoreCase("Huawei"))
        {
            sendToHuawei(context, count);
        }
        else if (Build.MANUFACTURER.equalsIgnoreCase("vivo"))
        {
            sendToVivo(context, count);
        }
        else if(isMiUi())
        {
            sendToXiaoMi(context, count);
        }
    }

    /**
     * 向索尼手机发送未读消息数广播<br/>
     * 据说：需添加权限：<uses-permission android:name=
     * "com.sonyericsson.home.permission.BROADCAST_BADGE" /> [未验证]
     * 
     * @param count
     */
    private static void sendToSony(Context context, int count)
    {
        count = count > 99 ? 99 : count;
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null)
        {
            return;
        }
        
        boolean isShow = (count != 0);
        
        Intent localIntent = new Intent();
        localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", isShow);// 是否显示
        localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);// 启动页
        localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));// 数字
        localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());// 包名
        context.sendBroadcast(localIntent);
    }
    
    /**
     * 向三星手机发送未读消息数广播
     * 
     * @param count
     */
    private static void sendToSamsumg(Context context, int count)
    {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null)
        {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count > 99 ? 99 : count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }
    
    /**
     * 向华为手机发送未读消息数广播<br/>
     * 需添加权限：    <uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" />
     *<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE" />
     * @param count
     */
    private synchronized static void sendToHuawei(Context context, int count)
    {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null)
        {
            return;
        }
        
        Bundle bundle = new Bundle();
        bundle.putString("package", context.getPackageName());
        bundle.putString("class", launcherClassName);
        bundle.putInt("badgenumber", count);
        
        try
        {
            context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"),
                    "change_badge", null, bundle);
        }
        catch (Exception e)
        {
            //Logger.error("sendToHuawei", "", e);
        }
    }
    
    /**
     * 向vivo手机发送未读消息数广播
     * 
     * @param count
     */
    private static void sendToVivo(Context context, int count)
    {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null)
        {
            return;
        }
        Intent intent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
        intent.putExtra("packageName", context.getPackageName());
        intent.putExtra("className", launcherClassName);
        intent.putExtra("notificationNum", count > 99 ? 99 : count);
        context.sendBroadcast(intent);
    }
    
    /**
     * 向小米手机发送未读消息数广播
     * 
     * @param count
     */
    private static void sendToXiaoMi(Context context, int count)
    {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null)
        {
            return;
        }
        NotificationManager nm = (NotificationManager) context.getSystemService(
                android.content.Context.NOTIFICATION_SERVICE);

        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(context, "channel_1");
            builder.setSmallIcon(R.drawable.ic_launcher);
            NotificationChannel channel = new NotificationChannel("channel_1", "familyMsg", NotificationManager.IMPORTANCE_DEFAULT);
            nm.createNotificationChannel(channel);
            notification = builder.build();
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setSmallIcon(R.drawable.ic_launcher);
            notification = builder.build();
        }

        nm.notify(R.string.app_name, notification);
        
        try
        {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, Math.max(0, Math.min(count, 99)));
        }
        catch (NoSuchFieldException e)
        {
            Logger.error("sendToXiaoMi", "", e);
        }
        
        catch (IllegalAccessException | IllegalArgumentException e)
        {
            Logger.error("sendToXiaoMi", "", e);
        }
        catch (NoSuchMethodException e)
        {
            Logger.error("sendToXiaoMi", "", e);
        }
        catch (InvocationTargetException e)
        {
            Logger.error("sendToXiaoMi", "", e);
        }
    }

    private static String getLauncherClassName(Context context)
    {
        PackageManager packageManager = context.getPackageManager();
        
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setPackage(context.getPackageName());
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        
        ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        
        if (info == null)
        {
            info = packageManager.resolveActivity(intent, 0);
        }
        
        return info.activityInfo.name;
    }
    
}